package com.itheima.health.controller;

import com.itheima.health.BusinessException;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderSettingService;
import com.itheima.health.utils.ImportUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("ordersetting")
@Slf4j
public class OrderSettingController {
    @DubboReference
    private OrderSettingService orderSettingService;

    /**
     * @Author: 位帅帅
     * @Date: 17:48 2021/1/9
     * @Params: [year, month]
     * @RerurnType: com.itheima.health.entity.Result
     * @Description: 查询预约数据
     */
    @GetMapping("findByMonth")
    public Result findByMonth(Integer year, Integer month) {
        log.info("[预约-查询]year: {}, month: {}", year, month);
        List<OrderSetting> orderSettingList = orderSettingService.findByMonth(year, month);
        List<Map<String, Object>> list = parseOrderSettingToMap(orderSettingList);
        log.info("[预约-查询]list: {}", list);
        return new Result(true, MessageConst.GET_ORDERSETTING_SUCCESS, list);
    }

    /**
     * @Author: 位帅帅
     * @Date: 19:38 2021/1/9
     * @Params: [file]
     * @RerurnType: com.itheima.health.entity.Result
     * @Description: 文件上传
     */
    @RequestMapping("upload")
    public Result upload(@RequestParam("excelFile") MultipartFile file) {
        log.info("[预约-上传]fileName: {}, size: {}" + file.getOriginalFilename(), file.getSize());
        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName)) {
            return new Result(false, MessageConst.UPLOAD_FAIL);
        }
        List<List<Object>> lists;
        try {
            if (fileName.endsWith(".xls")) {
                lists = ImportUtil.read2003Excel(file.getInputStream());
            } else {
                lists = ImportUtil.read2007Excel(file.getInputStream());
            }
            List<OrderSetting> orderSettingList = parseToOrderSettingList(lists);
            orderSettingService.add(orderSettingList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(true,MessageConst.UPLOAD_SUCCESS);
    }

    /**
     * @Author: 位帅帅
     * @Date: 12:50 2021/1/10
     * @Params: [orderSetting]
     * @RerurnType: com.itheima.health.entity.Result
     * @Description: 编辑预约数量
    */
    @PostMapping("editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting) {
        log.info("[预约-编辑预约人数]orderSetting: {}",orderSetting);
        orderSettingService.editNumberByDate(orderSetting);
        return new Result(true,MessageConst.ORDERSETTING_SUCCESS);
    }

    /**
     * @Author: 位帅帅
     * @Date: 19:39 2021/1/9
     * @Params: [lists]
     * @RerurnType: java.util.List<com.itheima.health.pojo.OrderSetting>
     * @Description: 将List<List<Object>>转换为List<OrderSetting>
    */
    private List<OrderSetting> parseToOrderSettingList(List<List<Object>> lists) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<OrderSetting> orderSettingList = new ArrayList<>();
        for (int i = 1; i < lists.size(); i++) {
            List<Object> list = lists.get(i);
            OrderSetting orderSetting = new OrderSetting();
            orderSetting.setOrderDate(sdf.parse((String) list.get(0)));
            orderSetting.setNumber(Integer.valueOf(String.valueOf(list.get(1))));
            orderSettingList.add(orderSetting);
        }
        return orderSettingList;
    }

    /**
     * @Author: 位帅帅
     * @Date: 17:55 2021/1/9
     * @Params: [orderSettingList]
     * @RerurnType: java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @Description: 将OrderSetting数据转换为map数据
     */
    private List<Map<String, Object>> parseOrderSettingToMap(List<OrderSetting> orderSettingList) {
        /*this.leftobj = [
                    { date: 3, number: 100, reservations: 0 },
                    { date: 4, number: 200, reservations: 0 },
                    { date: 5, number: 112, reservations: 0 },
                ];*/
        ArrayList<Map<String, Object>> mapList = new ArrayList<>();
        for (OrderSetting orderSetting : orderSettingList) {
            Map<String, Object> map = new HashMap<>();
            map.put("number",orderSetting.getNumber()==null?0:orderSetting.getNumber());
            map.put("reservations",orderSetting.getReservations()==null?0:orderSetting.getReservations());
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(orderSetting.getOrderDate());
            int date = calendar.get(Calendar.DAY_OF_MONTH);
            map.put("date",date);
            mapList.add(map);
        }
        return mapList;
    }

    private OrderSetting parseOrderSetting(Row row) {
        Date date = null;
        Integer number = null;
        try {
            if (null != row.getCell(0)) {
                date = row.getCell(0).getDateCellValue();
            }
            if (null != row.getCell(1)) {
                double numberValue = row.getCell(1).getNumericCellValue();
                number = Double.valueOf(numberValue).intValue();
            }
        } catch (IllegalStateException | NumberFormatException e) {
            log.error("[预约-上传]e: {}", e.getMessage());
            throw new BusinessException(String.format("数据格式错误,%s 第%d行", row.getSheet().getSheetName(), row.getRowNum() + 1));
        }
        if (null == date || null == number) {

        }
        return new OrderSetting(date, number);
    }
}
